<template>
  <div class="user-management">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" class="animated-button" @click="handleAdd">新增用户</el-button>
        </div>
      </template>

      <el-table :data="userList" border class="animated-table" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="role" label="角色" width="120">
          <template #default="{ row }">
            <el-tag :type="row.role === '超级管理员' ? 'danger' : 'info'">
              {{ row.role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
      class="animated-dialog"
    >
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="formType === 'edit'" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role">
            <el-option
              v-for="role in USER_ROLES"
              :key="role"
              :label="role"
              :value="role"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status">
            <el-option
              v-for="status in USER_STATUS"
              :key="status"
              :label="status"
              :value="status"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getUsers, addUser, updateUser, deleteUser } from '@/api/user'
import type { User } from '@/api/user'

const loading = ref(false)
const dialogVisible = ref(false)
const formType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const userList = ref<User[]>([])

// 使用 ref 而不是 as const
const USER_STATUS = ref(['启用', '禁用'])
const USER_ROLES = ref(['超级管理员', '普通用户'])

// 使用字面量类型
type UserStatus = '启用' | '禁用'
type UserRole = '超级管理员' | '普通用户'

interface UserForm {
  id?: number
  username: string
  nickname: string
  email: string
  phone: string
  role: UserRole
  status: UserStatus
  createTime?: string
}

// 初始化表单数据
const initUserForm = (): UserForm => ({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  role: '普通用户',
  status: '启用'
})

const userForm = reactive<UserForm>(initUserForm())

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 重置表单方法
const resetForm = () => {
  Object.assign(userForm, initUserForm())
}

const loadUsers = async () => {
  try {
    loading.value = true
    const res = await getUsers()
    if (res.code === 200) {
      userList.value = res.data
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('Load users error:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  formType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: User) => {
  formType.value = 'edit'
  Object.assign(userForm, row)
  dialogVisible.value = true
}

const handleDelete = async (row: User) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      type: 'warning'
    })
    if (row.id) {
      const res = await deleteUser(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        loadUsers()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }
  } catch {
    // 取消删除
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (formType.value === 'add') {
          const res = await addUser(userForm)
          if (res.code === 200) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            loadUsers()
          } else {
            ElMessage.error(res.message || '添加失败')
          }
        } else {
          const res = await updateUser(userForm)
          if (res.code === 200) {
            ElMessage.success('修改成功')
            dialogVisible.value = false
            loadUsers()
          } else {
            ElMessage.error(res.message || '修改失败')
          }
        }
      } catch (error) {
        console.error('Submit error:', error)
        ElMessage.error(formType.value === 'add' ? '添加失败' : '修改失败')
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  loadUsers()
})
</script>

<style lang="less" scoped>
.user-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.animated-table {
  .el-table__row {
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateX(5px);
      background-color: #f5f7fa !important;
    }
  }
}

.animated-button {
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  }
  
  &:active {
    transform: translateY(0);
  }
  
  &::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 5px;
    height: 5px;
    background: rgba(255, 255, 255, 0.5);
    opacity: 0;
    border-radius: 100%;
    transform: scale(1, 1) translate(-50%);
    transform-origin: 50% 50%;
  }
  
  &:focus:not(:active)::after {
    animation: ripple 1s ease-out;
  }
}

.animated-dialog {
  :deep(.el-dialog) {
    transform: scale(0.8);
    opacity: 0;
    transition: all 0.3s ease-out;
    
    &.dialog-fade-enter-active {
      transform: scale(1);
      opacity: 1;
    }
  }
  
  :deep(.el-form-item) {
    opacity: 0;
    transform: translateY(20px);
    animation: slideUp 0.3s ease forwards;
    
    &:nth-child(1) { animation-delay: 0s; }
    &:nth-child(2) { animation-delay: 0.1s; }
    &:nth-child(3) { animation-delay: 0.2s; }
    &:nth-child(4) { animation-delay: 0.3s; }
    &:nth-child(5) { animation-delay: 0.4s; }
    &:nth-child(6) { animation-delay: 0.5s; }
  }
}

@keyframes slideUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes ripple {
  0% {
    transform: scale(0);
    opacity: 1;
  }
  100% {
    transform: scale(2);
    opacity: 0;
  }
}
</style> 